<template>
  <div class="customlist">
<!--    搜索区域-->
    <div class="searchBox">
      <div class="searchItem">
        <el-select v-model="value" clearable>
          <el-option label="全部客户" value></el-option>
          <el-option label="重点客户" value="重点客户"></el-option>
          <el-option label="一般客户" value="一般客户"></el-option>
          <el-option label="放弃客户" value="放弃客户"></el-option>
        </el-select>
        <el-input
            placeholder="请输入内容"
            v-model="input"
            clearable
            @change="inputChange">
        </el-input>
      </div>
      <el-button type="success" @click="exportExcel">导出EXCEL</el-button>
    </div>
<!--    列表区-->
    <div class="customListBox">
      <el-table
          :data="tableData"
          style="width: 100%"
          max-height="480"
          ref="table"
          :border="true"
          :stripe="true"
          v-loading="loading"
          element-loading-text="拼命加载中,请稍等"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55"
            align="center">
        </el-table-column>
        <el-table-column
            fixed
            prop="id"
            label="编号"
            width="80">
        </el-table-column>
        <el-table-column
            prop="name"
            label="姓名"
            width="80">
        </el-table-column>
        <el-table-column
            prop="sex"
            label="性别"
            width="80"
            :formatter="formatterSex">
        </el-table-column>
        <el-table-column
            prop="phone"
            label="电话"
            width="120">
        </el-table-column>
        <el-table-column
            prop="weixin"
            label="微信"
            width="120"
            :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column
            prop="email"
            label="邮编"
            width="135">
        </el-table-column>
        <el-table-column
            prop="type"
            label="类别"
            width="100">
        </el-table-column>
        <el-table-column
            prop="address"
            label="地址">
        </el-table-column>
        <el-table-column
            prop="userName"
            label="业务员"
            width="100">
        </el-table-column>
        <el-table-column
            label="操作"
            width="210">
          <template slot-scope="scope">
            <!-- scope 对应的是 当前这一行所对应的那一条数据 -->
            <el-button
                @click="edit(scope)"
                type="default"
                size="small">
              编辑
            </el-button>
            <el-button
                @click="deleteRow(scope)"
                type="danger"
                size="small">
              删除
            </el-button>
            <el-button
                @click="openDraw(scope)"
                type="warning"
                size="small">
              回访
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
<!--    分页区-->
    <div class="pageBox">
      <el-pagination
          background
          layout="total, prev, pager, next"
          :total="total"
          :page-size.sync="limit"
          :current-page.sync="page"
          @current-change="changePage"
          @prev-click="changePage"
          @next-click="changePage">
      </el-pagination>
    </div>
<!--    回访抽屉区-->
    <div>
      <el-drawer
          title="回访信息"
          :visible.sync="drawer"
          size="50%">
        <div>
          <el-button @click="innerDrawer = true">新增回访</el-button>
          <!--里层抽屉-->
          <el-drawer
              :append-to-body="true"
              :visible.sync="innerDrawer"
              :before-close="handleClose">
            <div class="innerTable">
              <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="defForm">
                <el-form-item label="客户名称" prop="name">
                  <el-input v-model="ruleForm.name" disabled></el-input>
                </el-form-item>
                <el-form-item label="回访日期" required>
                  <el-col :span="11">
                    <el-form-item prop="visitTime">
                      <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.visitTime" style="width: 100%;"></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-form-item>
                <el-form-item label="回访信息" prop="visitText">
                  <el-input type="textarea" v-model="ruleForm.visitText" :rows="5"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm('ruleForm')">立即创建/修改</el-button>
                  <el-button @click="resetForm('ruleForm')">重置</el-button>
                  <el-button @click="back">取消</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-drawer>
        <!--外层表格-->
          <div class="outterTable">
            <template>
              <el-table
                  :data="visitData"
                  style="width: 100%"
                  :border="true"
                  :stripe="true"
                  max-height="550">
                <el-table-column
                    fixed
                    prop="visitTime"
                    label="日期"
                    width="100">
                </el-table-column>
                <el-table-column
                    prop="customerName"
                    label="姓名"
                    width="100">
                </el-table-column>
                <el-table-column
                    prop="visitText"
                    label="回访信息">
                </el-table-column>
                <el-table-column
                    fixed="right"
                    label="操作"
                    width="150">
                  <template slot-scope="obj">
                    <el-button
                        @click.native.prevent="updataVisit(obj)"
                        type="text"
                        size="small">
                      修改
                    </el-button>
                    <el-button
                        @click.native.prevent="deleteVisit(obj)"
                        type="text"
                        size="small">
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </div>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import {addvisit, deleteCustom, getCustomList, visitList, deleteVisit, updataVisit, getVisitInfo} from "../../../api/api";
import xlsx from 'xlsx'
import utils from "../../../assets/lib/utils";

export default {
  name: "custom",
  data() {
    return {
      // 搜索框数据
      input: '',
      value: '',
      // 列表数据
      tableData:[],
      // 加载
      loading:false,
      // 多选的存储数组
      multipleSelection: [],
      // 分页控制
      limit: 10,
      total: 0 ,
      page: 1,

      // 回访抽屉控制
      drawer: false,
      innerDrawer: false,
      // 抽屉外层表格数据
      visitData:[],
      // 抽屉内层表格数据
      ruleForm: {
        name: '',
        visitTime: '',
        visitText: '',
        // 存储用户的id
        id: '',
        visitId:''
      },
      rules: {
        visitTime: [
          { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
        ],
        visitText: [
          { required: true, message: '请填写活动形式', trigger: 'blur' }
        ]
      }

    }
  },
  created() {
    this.getCustomList();
  },
  methods: {
    handleSelectionChange(val) {
      // val存储的是选中的值
      this.multipleSelection = val;
    },
    // 搜索
    inputChange() {
      // 搜索后当前页面都回到第一页
      this.page = 1;
      this.getCustomList();
    },
    formatterSex(row) {
      //row 这一行的数据，
      //当前一列的数据
      //当前格的数据
      return row.sex == 0 ? '男' : '女';
    },
    // 发送ajax请求数据
    getCustomList() {
      this.loading = true;
      getCustomList({
        lx: 'all',
        type: this.value,
        search: this.input,
        limit: this.limit,
        page: this.page,
      }).then(data => {
        this.tableData = data.data;
        // 无论数据成功还是失败，都让选中项变为空
        this.multipleSelection = [];

        this.total = parseInt(data.total);
        this.page = parseInt(data.page);
        this.limit = parseInt(data.limit);

        this.loading = false;
      })
    },
    // 分页处理
    changePage(num) {
      this.page = num;
      this.getCustomList();
    },
    // 删除数据
    deleteRow(obj) {
      // obj $index 对应的是这条数据索引
      // obj.row  对应的是这一条数据
      // this.tableData.splice(obj.$index,1)
      // 点击删除时要进行询问
      this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击确定删除
        // 发送数据请求删除数据
        deleteCustom(obj.row.id).then(data => {
          // 将这条数据从前端删除
          this.tableData.splice(obj.$index,1)
          // 删除成功后再给用户提示
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 导出Excel表格
    async exportExcel() {
      let multipleSelection = this.multipleSelection
      if (multipleSelection.length === 0) {
        this.$message('请选择要导出的数据')
        return
      }
      // 添加一个加载动画
      const loading = this.$loading({
        lock: true,
        text: '正在加载，请稍后',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      await  utils.delay(500);

      // 将Json数据转换为表
      multipleSelection = utils.formatWeet(multipleSelection)
      let sheet = xlsx.utils.json_to_sheet(multipleSelection),
          book = xlsx.utils.book_new();
      xlsx.utils.book_append_sheet(book,sheet,'客户列表');
      xlsx.writeFile(book,`customlist${new Date().getTime()}.xlsx`);

      loading.close();
      this.multipleSelection = [];
      // 强制更新 （没效果）
      // this.$forceUpdate();
      // 清空之前选择的数据
      this.$refs.table.clearSelection();
    },
    // 前往新增用户界面进行用户信息修改
    edit(obj) {
      this.$router.push({
        path: '/crm/addCustom',
        query: {
          id: obj.row.id
        }
      })
    },

    // 请求回访数据
    visitList() {
      visitList(this.ruleForm.id).then(data => {
        this.visitData = data.data
      })
    },

    // 点击回访按钮，打开抽屉，并请求数据
    openDraw(obj) {
      this.ruleForm.id = obj.row.id
      this.ruleForm.name = obj.row.name
      this.drawer = true;
      this.visitList()
    },
    // 删除回访表格的数据
    deleteVisit(obj) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击确定删除
        // 发送数据请求删除数据
        deleteVisit(obj.row.id).then(data => {
          // // 将这条数据从前端删除
          this.visitData.splice(obj.$index,1)
          // 删除成功后再给用户提示
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 获取回访的详细信息
    getVisitInfo(id) {
      getVisitInfo(id).then(data => {
        this.ruleForm.visitText = data.data.visitText

        this.ruleForm.visitTime = new Date(data.data.visitTime)
        console.log(this.ruleForm.visitTime)
      })
    },
    // 修改回访信息
    updataVisit(obj) {
      this.innerDrawer = true
      this.getVisitInfo(obj.row.id)
      this.ruleForm.visitId = obj.row.id
    },

    //内层表格方法
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 先获取时间，进行格式化
          let visitTime = utils.dataFormat(this.ruleForm.visitTime)

          if(this.ruleForm.visitId) {
            console.log(1)
            updataVisit({
              visitId: this.ruleForm.visitId,
              customerId: this.ruleForm.id,
              visitText: this.ruleForm.visitText,
              visitTime: visitTime
            }).then(data => {
              if (data.code === 0) {
                // 修改成功
                this.$alert('修改成功', '提示', {
                  confirmButtonText: '确定',
                  callback: action => {
                    // 点击确定我们跳转到列表页
                    this.handleClose()
                    this.visitList()
                  }
                })
              }  else {
                this.$alert('修改失败', '提示', {
                  confirmButtonText: '确定',
                  callback: action => {}
                })
              }
            })
          } else {
            addvisit({
              customerId: this.ruleForm.id,
              visitText: this.ruleForm.visitText,
              visitTime: visitTime
            }).then(data => {
              // 添加成功
              if (data.code === 0) {
                // 新增成功
                this.$alert('新增成功', '提示', {
                  confirmButtonText: '确定',
                  callback: action => {
                    // 点击确定
                    this.handleClose()
                    this.visitList()
                  }
                })
              } else {
                this.$alert('新增失败', '提示', {
                  confirmButtonText: '确定',
                  callback: action => {}
                })
              }
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 点击取消返回外层抽屉
    back() {
      this.handleClose()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    // 回访里层抽屉关闭函数
    handleClose() {
      this.ruleForm.visitId = ''
      this.ruleForm.visitText = ''
      this.ruleForm.visitTime = ''
      this.innerDrawer = false
    }
  },
  watch: {
    value() {
      // 下拉框中值改变,就重新请求数据

      // 搜索后当前页面都回到第一页
      this.page = 1;
      this.getCustomList();
    },
    // 监听路由，判断是否要重新请求数据
    $route(to, from) {
      if (from.path === '/crm/uploadCustom' || from.path === '/crm/addCustom') {
        this.page = 1;
        this.input= '';
        this.value= '';
        this.getCustomList();
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .searchBox {
    margin-bottom: 10px;
    overflow: hidden;
    .searchItem {
      float: right;
    }
    .el-input {
      width: auto;
      margin-left: 20px;
    }
    .el-button {
      float: left;
    }
  }
  .pageBox {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-right: 20px;
    margin-top: 6px;
  }

  .outterTable {
    padding: 20px;
  }
  .defForm {
    width: 90%;
  }
</style>
